<?php

namespace App\Console\Commands\WorkOrder;

use App\Models\Common\ResourcesModel;
use App\Models\Recognize\RecognizeFoodProduceLicenseResult;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;
use Kuafu\File\PrivateFileUtil;
use Kuafu\Recognizer\FoodProduceLicenseRecognize;
use Kuafu\Recognizer\Recognizer;

class TransferFoodProduceLicenseImage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'work_order:transfer_food_produce_license_image';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '【工单】食品经营许可证-存下识别结果';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit','2048M');

        Log::info('TransferFoodProduceLicenseImage start...');

        ResourcesModel::query()
            ->where('module', ResourcesModel::MODULE_TYPE_WORK_ORDER)
            ->where('business', ResourcesModel::BUSINESS_WORK_ORDER_FUNCTION_OPEN)
            ->where('name', 'foodBusinessLicenseImg')
            ->orderBy('id')
            ->chunk(100, function ($models) {
                foreach ($models as $model) {
                    if (!strlen($model->url)) {
                        echo 'x';
                        continue;
                    }
                    //查询URL是否已入库
                    $id = RecognizeFoodProduceLicenseResult::query()
                        ->where('url', $model->url)
                        ->value('id');
                    if ($id) {
                        $this->info($model->id. '数据已存在');
                        continue;
                    }
                    $url     = ltrim(parse_url($model->url, PHP_URL_PATH), '/');
                    $suffix  = FileUtil::guessSuffix($url);
                    $fullUrl = $model->isPublic
                        ? FileUtil::domain() . '/' . $url
                        : PrivateFileUtil::signUrl($url);
                    $tmpFile = sys_get_temp_dir() . '/' . Str::random() . $suffix;
                    try {
                        (new Client())->get($fullUrl, [RequestOptions::SINK => $tmpFile]);
                    } catch (\Exception $e) {
                        @unlink($tmpFile);
                        echo 'x';
                        continue;
                    }
                    if (!is_readable($tmpFile)) {
                        echo 'x';
                        continue;
                    }
                    // 识别
                    $recognizer = new Recognizer(FoodProduceLicenseRecognize::getInstance());
                    try {
                        $rResult = $recognizer->recognizer($tmpFile);
                    } catch (\Exception $e) {
                        @unlink($tmpFile);
                        echo 'x';
                        continue;
                    }
                    if (!isset($rResult['data'])) {
                        @unlink($tmpFile);
                        echo 'x';
                        continue;
                    }
                    $resultModel     = RecognizeFoodProduceLicenseResult::add($model->url, $rResult['data']);
                    $this->info($model->id . '√');
                    Log::info("TransferFoodProduceLicenseImage:" . $model->id);
                    usleep(500000);
                }
            }
            );

        Log::info('TransferFoodProduceLicenseImage end...');

        return 0;
    }
}
